package com.fnfn.sdk.api.service.impl;

import java.util.Date;
import java.util.List;

import com.fnfn.sdk.api.common.MD5;
import com.fnfn.sdk.api.dao.RolePermissionMapper;
import com.fnfn.sdk.api.dao.UserMapper;
import com.fnfn.sdk.api.dao.UserPermissionMapper;
import com.fnfn.sdk.api.entity.User;
import com.fnfn.sdk.api.entity.UserPermission;
import com.fnfn.sdk.api.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fnfn.sdk.api.common.DateUtil;
import com.fnfn.sdk.api.dao.PermissionDetailMapper;
import com.fnfn.sdk.api.entity.RolePermission;

@Service("UserService")
public class UserServiceImpl implements UserService {

    Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    private UserMapper userMapper;
    private final UserPermissionMapper userPermissionMapper;
    private final RolePermissionMapper rolePermissionMapper;
    private final PermissionDetailMapper permissionDetailMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper, UserPermissionMapper userPermissionMapper,
                           RolePermissionMapper rolePermissionMapper, PermissionDetailMapper permissionDetailMapper) {
        this.userMapper = userMapper;
        this.userPermissionMapper = userPermissionMapper;
        this.rolePermissionMapper = rolePermissionMapper;
        this.permissionDetailMapper = permissionDetailMapper;
    }

    @Transactional
    @Override
    public void add(User user) throws Exception {
        short state = 1;
        user.setState(state);
        user.setStatus(2);
        user.setCreateTime(DateUtil.formatDateTime(new Date()));
        user.setcPassword(MD5.getStandardMd5(user.getcPassword()));
        if (user.getcRoleId() != null) {
            userMapper.insertSelective(user);
            List<RolePermission> list = rolePermissionMapper.groupByPermissionId(user.getcRoleId());
            for (RolePermission r : list) {
                UserPermission userPermission = new UserPermission();
                userPermission.setcUserId(user.getcUserId());
                userPermission.setcPermissionId(r.getcPermissionId());
                userPermissionMapper.insertSelective(userPermission);
            }
        }
    }

    @Override
    public User selectByUsername(String username) throws Exception {
        return userMapper.selectByUsername(username);
    }

    @Override
    public void remove(Integer userId) throws Exception {
        userMapper.removeByUserId(userId);
    }

    @Transactional
    @Override
    public void modify(User user) throws Exception {
        user.setUpdateTime(DateUtil.formatDateTime(new Date()));
        if (StringUtils.isBlank(user.getcPassword()) || StringUtils.isBlank(user.getOldPassword())) {
            user.setcPassword(null);
            user.setOldPassword(null);
        }
        userMapper.updateExcept(user);

        userPermissionMapper.deleteByUserId(user.getcUserId());
        if (user.getcRoleId() != null) {
            List<RolePermission> list = rolePermissionMapper.groupByPermissionId(user.getcRoleId());
            for (RolePermission r : list) {
                UserPermission userPermission = new UserPermission();
                userPermission.setcUserId(user.getcUserId());
                userPermission.setcPermissionId(r.getcPermissionId());
                userPermissionMapper.insertSelective(userPermission);
            }
        }
    }

    @Override
    public List<User> selectByCondition(User user) throws Exception {
//		if (StringUtils.isNotEmpty(user.getEndDate())) {
//			user.setEndDate(DateUtil.addDate(user.getEndDate(), 1));
//		}
        if (user.getStatus() != null && !user.getStatus().equals("")) {
            if (user.getStatus().equals(1)) {
                user.setStatus(null);
            }
        }

        return userMapper.selectByCondition(user);
    }

    @Override
    public User selectByUserId(Integer userId) throws Exception {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public void modifyPassword(User user) throws Exception {
        user.setUpdateTime(DateUtil.formatDateTime(new Date()));
        System.out.println("cpassword==============" + user.getcPassword());
        user.setcPassword(MD5.getStandardMd5(user.getcPassword()));
        System.out.println("cpassword==============" + user.getcPassword());
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public List<User> selectByDepartmentId(Integer cDepartmentId) throws Exception {
        return userMapper.selectByDepartmentId(cDepartmentId);
    }

    @Override
    public List<User> selectByRoleId(Integer cRoleId) throws Exception {
        return userMapper.selectByRoleId(cRoleId);
    }

    @Override
    public void saveAvatar(Integer userId, String fileName) throws Exception {
        User user = new User();
        user.setcUserId(userId);
        user.setcAvatar(fileName);
        user.setUpdateTime(DateUtil.formatDateTime(new Date()));
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public User selectDetailByUserId(Integer cUserId) throws Exception {
        return userMapper.selectDetailByUserId(cUserId);
    }

    @Override
    public User selectDetailByUsername(String cUsername) throws Exception {
        User user = userMapper.selectDetailByUsername(cUsername);
        if (user != null) {
            if (user.getcPermissions() != null) {
                for (int i = 0; i < user.getcPermissions().size(); i++) {
                    user.getcPermissions().get(i).setSubDetail(permissionDetailMapper
                            .selectByPermissionKey(user.getcPermissions().get(i).getcPermissionId()));
                }
            }
        } else {
            logger.warn("user is null,cUsername={}", cUsername);
        }

        return user;
    }

    @Override
    public List<User> selectAll(User user) throws Exception {
        return userMapper.selectAll(user);
    }


    @Override
    public int modifyStatus(User user) throws Exception {
        return userMapper.modifyStatus(user);
    }

}
